package com.llt.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 1. 每个服务 访问2次换下一个服务
 * total = 0 total==2 指向下一节点
 * index = 0 默认节点选择1
 *
 */
public class LltRandomRule extends AbstractLoadBalancerRule {
    private int total=0;//被调用的次数
    private int currentIndex=0;//当前谁在提供服务
    public LltRandomRule() {
    }

    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

//                int index = this.chooseRandomInt(serverCount);
//                server = (Server)upList.get(index);
                //=================自定义======================
//                int currentindex = this.chooseRandomInt(serverCount);

                if (total<1){
                    server = upList.get(total);
                    total++;
                }else {
                 total = 0;
//                    currentIndex=currentIndex+1;
//                    if(currentIndex>=upList.size());{
//                        currentIndex = 0;
//                    }
                    server = upList.get(total);
                }
                System.out.println("total:==="+total);
                System.out.println("upList.size():==="+upList.size());
                //=================自定义======================
                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {

        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
